﻿using System;
using Microsoft.SharePoint;

namespace WoltersKluwer.SPChainGang.Core.Data.Repository
{
    class ListResolver : IDisposable
    {
        private readonly string siteUrl;
        private readonly string listName;
        private readonly Guid listId;
        private readonly bool needDispose;
        private SPList list;
        private SPSite site;
        private SPWeb web;

        private ListResolver(SPWeb web)
        {
            this.web = web;
        }

        public ListResolver(String siteUrl, String listName)
        {
            this.siteUrl = siteUrl;
            this.listName = listName;
            needDispose = true;
        }

        public ListResolver(SPWeb web, String listName) : this(web)
        {
            this.listName = listName;
        }

        public ListResolver(SPWeb web, Guid listId) : this(web)
        {
            this.listId = listId;
        }

        public SPList List
        {
            get
            {
                if (list == null)
                {
                    if (web == null)
                    {
                        site = new SPSite(siteUrl);
                        web = site.OpenWeb();
                    }
                    list = String.IsNullOrEmpty(listName) ? web.Lists[listId] : web.Lists[listName];
                }
                return list;
            }
        }

       public void Dispose()
        {
           if (!needDispose) 
               return;

           if (web != null)
               web.Dispose();

           if (site != null)
               site.Dispose();
        }
    }
}
